﻿var upcomingEventslistItems;
var upcomingEventsquery;
var upcomingEventstargetList;
var upcomingEventsclientContext;
var upcomingEventsIsLoaded = false;
(function ($) {

    $(function () {
        var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.js", function () {
            $.getScript(scriptbase + "SP.Taxonomy.js", getupcomingEvents('upcomingEvents'));
            $.getScript(scriptbase + "SP.Taxonomy.js", loadmoredata());
        });
    });

    this.loadmoredata = function () {
        $(window).scroll(function () {
            if ($(window).scrollTop() - ($(document).height() - $(window).height() - 190) < 90 && $(window).scrollTop() - ($(document).height() - $(window).height() - 190) > 0) {
                if (upcomingEventsIsLoaded) {
                    getmoreupcomingEvents('upcomingEvents');
                }
            }
        });
    };

    this.getupcomingEvents = function (idupcomingEvents) {
        upcomingEventsIsLoaded = false;
        $('#upcomingEventsloading').show();
        var siteUrl = window.location.protocol + '//' + window.location.host + '/teams/OurVoiceHN/UpcomingEvents/';
        upcomingEventsclientContext = new SP.ClientContext(siteUrl);
        upcomingEventstargetList = upcomingEventsclientContext.get_web().get_lists().getByTitle('Posts');
        upcomingEventsquery = new SP.CamlQuery();

        var catId = getParameterByName('CategoryId');

        if (catId == "") {
            upcomingEventsquery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq><Geq><FieldRef Name=\'PublishedDate\' /><Value Type=\'DateTime\'><Today /></Value></Geq></And></Where><OrderBy><FieldRef Name=\'Top_x0020_News\' Ascending=\'FALSE\' /><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>6</RowLimit></View>');
        }
        else {
            upcomingEventsquery.set_viewXml('<View><Query><Where><And><And><Geq><FieldRef Name=\'PublishedDate\' /><Value Type=\'DateTime\'><Today /></Value></Geq><Contains><FieldRef Name=\'PostCategory\' LookupId=\'TRUE\' /><Value Type=\'LookupMulti\'>' + parseInt(catId) + '</Value></Contains></And><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq></And></Where><OrderBy><FieldRef Name=\'Top_x0020_News\' Ascending=\'FALSE\' /><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>6</RowLimit></View>');
        }

        upcomingEventslistItems = upcomingEventstargetList.getItems(upcomingEventsquery);
        //upcomingEventsclientContext.load(upcomingEventslistItems, "Include(ID,Title,Summary,PublishingPageIcon,NumComments,PostCategory,PublishedDate,Author)");
        upcomingEventsclientContext.load(upcomingEventslistItems);

        upcomingEventsclientContext.executeQueryAsync(
            function () {
                $('#upcomingEventsloading').hide();
                upcomingEventsIsLoaded = true;
                $('#' + idupcomingEvents).html('');

                //create json array to keep calendar collections
                var calendarCollections = [];
                var listEnumerator = upcomingEventslistItems.getEnumerator();
                var index = 0;
                var j = 0;
                var result = '';
                var calendaritemstring = '';
                var count = 0;

                while (listEnumerator.moveNext()) {
                    count++;

                    var calendarId = 'msCalendar_' + count;
                    var addToCalendarId = 'addToCalendar_' + count;

                    var item = listEnumerator.get_current();
                    var url = siteUrl + 'Lists/Posts/Post.aspx?ID=' + item.get_item('ID');
                    //var userlink = siteUrl + '_layouts/15/userdisp.aspx?ID=' + item.get_item('Author').get_lookupId();

                    //build number of comments
                    var numCommentsValue = item.get_item('NumComments');
                    var totalcomment = numCommentsValue.get_lookupId();
                    var categoryLink = '#';
                    var categoryname = '';

                    //get values
                    var titleValue = item.get_item('Title');
                    var locationValue = item.get_item('Location');
                    if (locationValue == null) locationValue = '';
                    var startDate = item.get_item('PublishedDate');
                    var description = item.get_item('Summary');

                    if (item.get_item('PostCategory')[0] != null) {
                        categoryLink = siteUrl + 'Lists/Categories/Category.aspx?CategoryId=' + item.get_item('PostCategory')[0].get_lookupId();
                        categoryname = item.get_item('PostCategory')[0].get_lookupValue();
                    }

                    var calendar = buildnewscomingupEvents(startDate, item.get_item('Title'), item.get_item('PublishingPageIcon'), item.get_item('Summary'), url, categoryLink, categoryname, totalcomment, calendarId, addToCalendarId);

                    if (index % 3 == 0) {
                        calendaritemstring += '<div class="row">';
                        calendaritemstring += calendar;
                        j = 1;
                    }
                    else {
                        calendaritemstring += calendar;
                        j += 1;
                    }

                    if (j == 3) {
                        calendaritemstring += '</div>';
                    }
                    index = index + 1;

                    //push data into json 
                    calendarCollections.push({ titleValue: titleValue, locationValue: locationValue, startDate: startDate, description: description, calendarId: calendarId, addToCalendarId: addToCalendarId });
                }

                result = calendaritemstring;

                if (j != 3) {
                    result += '</div>';
                }

                if (index > 0) {
                    $('#' + idupcomingEvents).append(result);
                }
                else {
                    $('#' + idupcomingEvents).html('There are no posts in this category.');
                }
                //----Add to my calendar
                AddToOutlook(calendarCollections);
            }, function (sender, args) {
                console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };

    this.getmoreupcomingEvents = function (idupcomingEvents) {
        upcomingEventsIsLoaded = false;
        var siteUrl = window.location.protocol + '//' + window.location.host + '/teams/OurVoiceHN/UpcomingEvents/';
        //Gets the id of the last element from the returned collection along with the query. 
        var position = upcomingEventslistItems.get_listItemCollectionPosition();
        if (position != null) {
            $('#upcomingEventsloading').show();
            upcomingEventsquery.set_listItemCollectionPosition(position);
            upcomingEventslistItems = upcomingEventstargetList.getItems(upcomingEventsquery);
            //upcomingEventsclientContext.load(upcomingEventslistItems, "Include(ID,Title,Location,Summary,PublishingPageIcon,NumComments,PostCategory,PublishedDate,Author)");
            upcomingEventsclientContext.load(upcomingEventslistItems);
            upcomingEventsclientContext.executeQueryAsync(function () {
                upcomingEventsIsLoaded = true;
                $('#upcomingEventsloading').hide();
                var listEnumerator = upcomingEventslistItems.getEnumerator();
                var index = 0;
                var j = 0;
                var result = '';
                var calendaritemstring = '';

                var calendarCollections = [];
                while (listEnumerator.moveNext()) {
                    var item = listEnumerator.get_current();
                    var url = siteUrl + 'Lists/Posts/Post.aspx?ID=' + item.get_item('ID');
                   // var userlink = siteUrl + '_layouts/15/userdisp.aspx?ID=' + item.get_item('Author').get_lookupId();

                    //get values
                    var titleValue = item.get_item('Title');
                    var locationValue = item.get_item('Location');
                    if (locationValue == null) locationValue = '';

                    var startDate = item.get_item('PublishedDate');
                    var endDate = item.get_item('PublishedDate');
                    var description = item.get_item('Summary');

                    //build number of comments
                    var numCommentsValue = item.get_item('NumComments');
                    var totalcomment = numCommentsValue.get_lookupId();
                    var categoryLink = '#';
                    var categoryname = '';
                    if (item.get_item('PostCategory')[0] != null) {
                        categoryLink = siteUrl + 'Lists/Categories/Category.aspx?CategoryId=' + item.get_item('PostCategory')[0].get_lookupId();
                        categoryname = item.get_item('PostCategory')[0].get_lookupValue();
                    }
                    var calendar = buildnewscomingupEvents(new Date(item.get_item('PublishedDate')), item.get_item('Title'), item.get_item('PublishingPageIcon'), item.get_item('Summary'), url, categoryLink, categoryname, totalcomment);
                    if (index % 3 == 0) {
                        calendaritemstring += '<div class="row">';
                        calendaritemstring += calendar;
                        j = 1;
                    }
                    else {
                        calendaritemstring += calendar;
                        j += 1;
                    }
                    if (j == 3) {
                        calendaritemstring += '</div>';
                    }
                    index = index + 1;

                    //push data into json 
                    calendarCollections.push({ titleValue: titleValue, locationValue: locationValue, startDate: startDate, description: description, calendarId: calendarId, addToCalendarId: addToCalendarId });
                }
                result = calendaritemstring;
                if (j != 3)
                { result += '</div>'; }
                $('#' + idupcomingEvents).append(result).fadeIn(1000);
                //----Add to my calendar
                AddToOutlook(calendarCollections);
            }, function (sender, args) {
                console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
       );
        }

    };

    this.buildnewscomingupEvents = function (dateCalendar, author, pathurl, sumary, urlitem, categorylink, categoryname, totalcomment, calendarId, addToCalendarId) {
        var sum = "";
        if (sumary != null) {
            sum = sumary;
        }

        if (sum.length > 150) {
            sum = sum.substring(0, 150) + '...';
        }

        var imgUrl = '';
        if (pathurl != null && $(pathurl).attr('src') != '') {
            imgUrl = $(pathurl).attr('src') + '?RenditionID=9';
        }
        else {
            imgUrl = '/teams/OurVoiceHN/Style Library/Images/default_image.gif?RenditionID=9';
        }

        if (totalcomment == "") {
            totalcomment = "0";
        }
        if (author == null)
            author = "";
        var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'];
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

        var result = '<div class="calendaritem col-sm-4 col-md-4 col-lg-4">';
        result += '<div class="row">';
        result += '<div class="titleCalendar col-sm-12 col-md-12 col-lg-12">';
        result += '<div class="dateSection">';
        result += '<h5 class="dayCalendar">' + days[dateCalendar.getDay()] + '</h5>';
        result += '<h3 class="dateCalendar">' + dateCalendar.getDate() + '</h3>';
        result += '<h5 class="monthCalendar">' + months[dateCalendar.getMonth()] + '</h5>';
        result += '</div>';
        result += '<div class="author">' + author + '</div>';
        result += '</div>';

        result += '<div class="col-sm-12 col-md-12 col-lg-12"><a href="' + urlitem + '"><img class="img-responsive" src="' + imgUrl + '" /></a></div>';

        result += '<div class="calendarTime col-sm-12 col-md-12 col-lg-12">';
        result += '<div class="time pull-left">' + formatAMPM(dateCalendar) + ' | <span class="totalcomment"> ' + totalcomment + ' comments</span></div>';

        result += '<div id=\"' + addToCalendarId + '" class="addToCalendar pull-right"></div>';
        result += '<div id=\"' + calendarId + '\"></div>';

        result += '</div>';

        result += '<div class="caption col-sm-12 col-md-12 col-lg-12">';
        result += '<p class="content">' + sum + '</p>';
        result += '<a class="moreInfor" href="' + urlitem + '">More »</a>';
        result += '</div>';

        result += '</div>';
        result += '</div>';
        return result;
    };

    this.formatAMPM = function (date) {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        return strTime;
    };

    this.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    this.AddToOutlook = function (calendarCollections) {
        //------Add to my calendar

        if (calendarCollections.length > 0) {
            $.each(calendarCollections, function (indexx, valuex) {

                var titleValue = valuex.titleValue.toString();
                var locationValue = valuex.locationValue.toString();
                var startDate = valuex.startDate.toString();
                var descriptionValue = valuex.description.toString();
                var calendarIdValue = valuex.calendarId.toString();
                var addToCalendarIdValue = valuex.addToCalendarId.toString();

                var myCalendar = createCalendar({
                    options: {
                        id: calendarIdValue                               // You need to pass an ID. If you don't, one will be generated for you.
                    },
                    data: {
                        title: titleValue,     // Event title
                        start: new Date(startDate),   // Event start date
                        duration: 120,                            // Event duration (IN MINUTES)
                        end: new Date(startDate),     // You can also choose to set an end time.
                        // If an end time is set, this will take precedence over duration
                        address: locationValue,
                        description: descriptionValue.replace(/(\r\n|\n\r|\r|\n)/g, " ")
                    }
                });

                document.querySelector('#' + calendarIdValue).appendChild(myCalendar);

                //remove redundant icons
                var iconoutlookClass = $('#' + calendarIdValue).find('a.icon-outlook');
                if (iconoutlookClass !== null && iconoutlookClass.length > 0) {
                    iconoutlookClass.text('Add to outlook');
                    $('#' + addToCalendarIdValue).html(iconoutlookClass);

                    if ($('#' + calendarIdValue).length > 0) $('#' + calendarIdValue).remove();
                }
            });
        }

    };

    /*end javascript for get comingup events*/
    /*=======================================*/
}).call(this, jQuery);